const path = require("path");

// 代码打包之后取出console.log压缩代码
const TerserPlugin = require("terser-webpack-plugin");
// gzip压缩插件
const CompressionWebpackPlugin = require("compression-webpack-plugin");
// // 图形化打包详情
// const BundleAnalyzerPlugin =
//   require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
// 分析打包时间
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const isProduction = process.env.NODE_ENV === "production";
function resolve(dir) {
  return path.join(__dirname, dir);
}

module.exports = {
  publicPath: "./",
  // 打包文件的出口
  // 放置生成的css和js和img和fonts的目录
  assetsDir: "static",
  outputDir: isProduction ? "dist/production" : "dist/test",
  chainWebpack: (config) => {
    // isProduction &&
    // config.plugin("webpack-bundle-analyzer").use(BundleAnalyzerPlugin);
    // 定义文件夹的路径
    config.resolve.alias
      .set("@", resolve("src"))
      .set("assets", resolve("src/assets"))
      .set("components", resolve("src/components"))
      .set("router", resolve("src/router"))
      .set("store", resolve("src/store"))
      .set("views", resolve("src/views"));
  },

  //打包后是否生成map文件，map文件能看到错误代码位置，设置为false不生成map文件，打包体积缩小
  productionSourceMap: false,

  // webpack的配置
  configureWebpack: (config) => {
    // 生产环境配置
    if (process.env.NODE_ENV === "production") {
      // 代码压缩去除console.log
      config.plugins.push(
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ["console.log"], // 移除console1
            },
          },
        })
      );
    }
    // 开启gzip压缩
    config.plugins.push(
      new SpeedMeasurePlugin(),
      // new BundleAnalyzerPlugin(),
      new CompressionWebpackPlugin({
        filename: (info) => {
          return `${info.path}.gz${info.query}`;
        },
        algorithm: "gzip",
        threshold: 10240, // 只有大小大于该值的资源会被处理 10240
        test: new RegExp("\\.(" + ["js"].join("|") + ")$"),
        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
        deleteOriginalAssets: false, // 删除原文件
      }),
      new CompressionWebpackPlugin({
        filename: (info) => {
          return `${info.path}.br${info.query}`;
        },
        algorithm: "brotliCompress",
        threshold: 10240, // 只有大小大于该值的资源会被处理 10240
        test: new RegExp("\\.(" + ["js"].join("|") + ")$"),
        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
        deleteOriginalAssets: false, // 删除原文件
      })
    );
  },
};
